//
//  ExamWriteViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/21.
//

#import "ExamWriteViewController.h"
#import "ErrorCorrectionViewController.h"
#import "ExamQuestionModel.h"
#import "ExamPaperQuestionManager.h"
#import "ExamQuestionOptionsModel.h"
#import "CollectSaveManager.h"
#import "WordCollectDeleteManager.h"
#import <WebKit/WebKit.h>


@interface ExamWriteViewController ()<JPAPIManagerCallBackDelegate,WKUIDelegate,WKNavigationDelegate>

@property(nonatomic,strong)UIScrollView *bgScrollView;
@property(nonatomic,strong)WKWebView *titleWebView;
//@property(nonatomic,strong)UIView *tipBgView;
//@property(nonatomic,strong)UILabel *tipLabel;
@property(nonatomic,strong)UIView *exampleBgView;
@property(nonatomic,strong)UILabel *exampleTitleLabel;
@property(nonatomic,strong)ExamPaperQuestionManager *questionManager;
@property(nonatomic,strong)ExamQuestionModel *questionModel;
@property(nonatomic,strong)CollectSaveManager *collectSaveManager;
@property(nonatomic,strong)WordCollectDeleteManager *collectDeleteManager;
@property(nonatomic,strong)UIButton *collectBtn;
@property(nonatomic,strong)WKWebView *exampleWebView;
@property(nonatomic,assign)CGFloat total_h;
@property(nonatomic,strong)UIView *questionView;
@property(nonatomic,strong)WKWebView *questionWebView;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)UILabel *titleLabel;


@end

@implementation ExamWriteViewController

-(ExamPaperQuestionManager *)questionManager{
    if(!_questionManager){
        _questionManager = [[ExamPaperQuestionManager alloc]init];
        _questionManager.delegate = self;
    }
    return _questionManager;
}

-(CollectSaveManager *)collectSaveManager{
    if(!_collectSaveManager){
        _collectSaveManager = [[CollectSaveManager alloc]init];
        _collectSaveManager.delegate = self;
    }
    return _collectSaveManager;
}

-(WordCollectDeleteManager *)collectDeleteManager{
    if(!_collectDeleteManager){
        _collectDeleteManager = [[WordCollectDeleteManager alloc]init];
        _collectDeleteManager.delegate = self;
    }
    return _collectDeleteManager;
}


-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
    [self loadQuestionData];
}

#pragma mark - 获取专项测试数据
-(void)loadQuestionData{
    self.questionManager.paperId = self.paperModel.paperId;
    self.questionManager.type = self.typeModel?self.typeModel.ptId:@"";
    [self.questionManager loadData];
}

#pragma mark - 试题收藏和取消收藏
-(void)collectOrDeleteQuestionWithModel:(ExamQuestionModel*)model{
    if(self.collectBtn.selected == YES){
        //取消
        self.collectDeleteManager.collectId = model.collectId;
        [self.collectDeleteManager loadData];
    }else{
        //收藏
        self.collectSaveManager.wordId = model.questionId;
        self.collectSaveManager.type = @"2";
        [self.collectSaveManager loadData];
    }
}

-(void)createUI{
    
    self.customNavigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.textColor = KFontBlackColor;
    self.titleLabel.font = JPUIFontPingFangSCMedium(17);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = self.paperModel.name;
    [self.customNavigationBar addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@40);
        make.right.mas_equalTo(@-40);
        make.bottom.mas_equalTo(@-5);
        make.height.mas_equalTo(@34);
    }];
    
    self.bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT)];
    self.bgScrollView.backgroundColor = [UIColor whiteColor];
    self.bgScrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.bgScrollView];
    
    //大题题目
    self.questionView = [[UIView alloc]initWithFrame:CGRectMake(16,14,self.currentAvailableWidth-32,0)];
    self.questionView.layer.cornerRadius = 10;
    self.questionView.layer.masksToBounds = YES;
    self.questionView.backgroundColor = UIColorHex_(0xFF781D,0.1);
    [self.bgScrollView addSubview:self.questionView];
    
    [self createWebView];
    
    
    __weak typeof(self)weakSelf = self;
    //范文
    self.exampleBgView = [[UIView alloc]initWithFrame:CGRectMake(16,CGRectGetMaxY(self.titleWebView.frame)+21,self.currentAvailableWidth-32, 53+16)];
    self.exampleBgView.backgroundColor = KbgColor;
    self.exampleBgView.layer.cornerRadius = 10;
    self.exampleBgView.layer.masksToBounds = YES;
    [self.bgScrollView addSubview:self.exampleBgView];
    self.exampleTitleLabel = [[UILabel alloc]init];
    self.exampleTitleLabel.font = JPUIFontPingFangSCMedium(15);
    self.exampleTitleLabel.textColor = KFontBlackColor;
    self.exampleTitleLabel.text = @"范文：";
    [self.exampleBgView addSubview:self.exampleTitleLabel];
    [self.exampleTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.top.mas_equalTo(@16);
        make.height.mas_equalTo(@21);
        make.width.mas_equalTo(weakSelf.currentAvailableWidth-64);
    }];
    
    [self createExampleWebView];
  
    CGFloat h = 16+21+53+16+16+93;
    self.total_h = h;
    self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,h);
    
    UIView *bottomView = [[UIView alloc]init];
    bottomView.backgroundColor = [UIColor whiteColor];
    bottomView.layer.cornerRadius = 58/2.0;
    bottomView.layer.shadowColor = UIColorHex_(0x000000,0.25).CGColor;
    bottomView.layer.shadowOffset = CGSizeMake(0,0);
    bottomView.layer.shadowOpacity = 1;
    bottomView.layer.shadowRadius = 10;
    [self.view addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@208);
        make.height.mas_equalTo(@58);
        make.centerX.mas_equalTo(weakSelf.view);
        make.bottom.mas_equalTo(@-35);
    }];
    
    NSArray *imageArr = @[@"exam_question_uncollect",@"exam_question_error_list"];
    for (NSInteger i = 0; i < imageArr.count; i++){
        UIButton *btn = [[UIButton alloc]init];
        [btn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        if(i == 0){
            [btn setImage:[UIImage imageNamed:@"exam_question_collect"] forState:UIControlStateSelected];
            btn.selected = NO;
        }
        btn.tag = 666+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:btn];
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.height.mas_equalTo(@44);
            if(i == 0){
                make.left.mas_equalTo(@30);
            }else{
                make.right.mas_equalTo(@-30);
            }
            make.centerY.mas_equalTo(bottomView);
        }];
        if(i == 0){
            self.collectBtn = btn;
        }
    }
    
    self.bottomView = bottomView;
    
}

#pragma mark - 创建webview
-(void)createWebView{
    NSString *jScript0 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 64];
    WKUserScript *wkUScript0 = [[WKUserScript alloc] initWithSource:jScript0 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController0 = [[WKUserContentController alloc] init];
    [wkUController0 addUserScript:wkUScript0];
    WKWebViewConfiguration *wkWebConfig0 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig0.userContentController = wkUController0;
    self.questionWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16, 10, self.currentAvailableWidth - 64,0) configuration:wkWebConfig0];
    self.questionWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.questionWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.questionWebView.UIDelegate = self;
    self.questionWebView.navigationDelegate = self;
    self.questionWebView.scrollView.bounces = NO;
    self.questionWebView.backgroundColor = [UIColor clearColor];
    self.questionWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.questionWebView.scrollView.scrollEnabled = NO;
    self.questionWebView.opaque = NO;
    [self.questionView addSubview:self.questionWebView];
    self.questionView.hidden = YES;
    
    //写作题目
    NSString *jScript = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 40];
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
    self.titleWebView = [[WKWebView alloc]initWithFrame:CGRectMake(20,16,self.currentAvailableWidth-40,0) configuration:wkWebConfig];
    self.titleWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.titleWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.titleWebView.UIDelegate = self;
    self.titleWebView.navigationDelegate = self;
    self.titleWebView.scrollView.bounces = NO;
    self.titleWebView.backgroundColor = [UIColor clearColor];
    self.titleWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.titleWebView.scrollView.scrollEnabled = NO;
    self.titleWebView.opaque = NO;
    [self.bgScrollView addSubview:self.titleWebView];
    
}

-(void)createExampleWebView{
    
    NSString *jScript2 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 64];
    WKUserScript *wkUScript2 = [[WKUserScript alloc] initWithSource:jScript2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController2 = [[WKUserContentController alloc] init];
    [wkUController2 addUserScript:wkUScript2];
    WKWebViewConfiguration *wkWebConfig2 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig2.userContentController = wkUController2;
    self.exampleWebView = [[WKWebView alloc]initWithFrame:CGRectMake(16,53,self.currentAvailableWidth-64,0) configuration:wkWebConfig2];
    self.exampleWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.exampleWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.exampleWebView.UIDelegate = self;
    self.exampleWebView.navigationDelegate = self;
    self.exampleWebView.scrollView.bounces = NO;
    self.exampleWebView.backgroundColor = [UIColor clearColor];
    self.exampleWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.exampleWebView.scrollView.scrollEnabled = NO;
    self.exampleWebView.opaque = NO;
    [self.exampleBgView addSubview:self.exampleWebView];
   
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 获取当前可用宽度并更新布局
            self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
            self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
            self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
            self.bgScrollView.frame  = CGRectMake(0,kYM_NAVIGATIONBAR_HEIGHT,self.currentAvailableWidth,self.currentAvailableHeight-kYM_NAVIGATIONBAR_HEIGHT);
            self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,0);
            if(self.questionView){
                [self.questionWebView removeFromSuperview];
                self.questionWebView = nil;
            }
            if(self.titleWebView){
                [self.titleWebView removeFromSuperview];
                self.titleWebView = nil;
            }
            [self createWebView];
            self.exampleBgView.frame =  CGRectMake(16,CGRectGetMaxY(self.titleWebView.frame)+21,self.currentAvailableWidth-32, 53+16);
            __weak typeof(self)weakSelf = self;
            [self.exampleTitleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(weakSelf.currentAvailableWidth-64);
            }];
            
            if(self.exampleWebView){
                [self.exampleWebView removeFromSuperview];
                self.exampleWebView = nil;
            }
            [self createExampleWebView];
            
            self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,self.total_h);
            
            [self refreshUI];
            
            [self.view bringSubviewToFront:self.bottomView];

        });
    }
}

#pragma mark - 收藏 错误反馈点击
-(void)btnClick:(UIButton*)button{
    
    NSInteger index = button.tag-666;
    if(index == 0){
        //收藏
        if(self.questionModel){
            [self collectOrDeleteQuestionWithModel:self.questionModel];
        }
    }else if (index == 1){
        //错误反馈
        ErrorCorrectionViewController *vc = [[ErrorCorrectionViewController alloc]init];
        vc.type = 2;
        vc.paperModel = self.paperModel;
        vc.questionModel = self.questionModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

#pragma mark - 刷新界面
-(void)refreshUI{
    if(self.questionModel){
        if([self.questionModel.collect isEqualToString:@"1"]){
            self.collectBtn.selected = YES;
        }else{
            self.collectBtn.selected = NO;
        }
        CGFloat h = 16+21+53+16+16+93;
        if(self.questionModel.name &&![self.questionModel.name isEqualToString:@""]){
            self.questionView.hidden = NO;
            NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 14px; color: #FF781D;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
            NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle,self.questionModel.name];
            if(![self.questionModel.name containsString:@"<p>"]){
                fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle,self.questionModel.name];
            }
            [self.questionWebView loadHTMLString:fullHTML baseURL:nil];
           h = h-16+14+self.questionView.height+24;
        }else{
            self.questionView.hidden = YES;
        }
        
        NSString *htmlContent = self.questionModel.content?self.questionModel.content:@"<p></p>";
        // 题目序号
        NSString *titleNumber = @"";
        if(self.questionModel.sortId&&![self.questionModel.sortId isEqualToString:@""]){
            titleNumber = [NSString stringWithFormat:@"%@.",self.questionModel.sortId];
        }
        // 查找第一个 <p> 标签的位置
        NSRange pTagRange = [htmlContent rangeOfString:@"<p>"];
        // 根据是否找到 <p> 标签进行处理
        NSString *combinedHTMLContent;
        if (pTagRange.location != NSNotFound) {
            // 找到 <p> 标签，插入序号
            combinedHTMLContent = [htmlContent stringByReplacingCharactersInRange:NSMakeRange(pTagRange.location + pTagRange.length, 0) withString:titleNumber];
        } else {
            // 未找到 <p> 标签，直接在字符串前面拼接序号
            combinedHTMLContent = [NSString stringWithFormat:@"<p>%@%@</p>",titleNumber, htmlContent];
        }

        // 设置样式
        NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E;letter-spacing: 1px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
        NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle, combinedHTMLContent];
        [self.titleWebView loadHTMLString:fullHTML baseURL:nil];
               
        NSString *paddingStyle2 = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E;letter-spacing: 1px;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
        NSString *fullHTML2 = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle2, self.questionModel.analysis];
        if(![self.questionModel.analysis containsString:@"<p>"]){
            fullHTML2 = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle2, self.questionModel.analysis];
        }
        [self.exampleWebView loadHTMLString:fullHTML2 baseURL:nil];
        self.total_h = h;
        self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,h);
    }
}

#pragma mark - webview delegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // 执行 JavaScript 以获取页面内容的高度
    [webView evaluateJavaScript:@"document.documentElement.scrollHeight" completionHandler:^(id result, NSError *error) {
        if (!error) {
            CGFloat height = [result doubleValue];
            CGFloat h = height-16;
            if(h < 0){
                h = 0;
            }
            if ([webView isEqual:self.titleWebView]) {
                if(self.questionWebView.height > 0){
                    webView.frame = CGRectMake(16,CGRectGetMaxY(self.questionView.frame)+24,self.currentAvailableWidth-40,h);
                }else{
                    webView.frame = CGRectMake(16,16,self.currentAvailableWidth-40,h);
                }
                self.total_h = self.total_h+h;
                self.exampleBgView.top = CGRectGetMaxY(self.titleWebView.frame)+21;
            }else if ([webView isEqual:self.exampleWebView]){
                webView.frame = CGRectMake(16,53,self.currentAvailableWidth-64,h);
                self.exampleBgView.frame = CGRectMake(16,CGRectGetMaxY(self.titleWebView.frame)+21,self.currentAvailableWidth-32,53+16+h);
                self.total_h = self.total_h+h;
            }else if ([webView isEqual:self.questionWebView]){
                webView.frame = CGRectMake(16,10,self.currentAvailableWidth - 64,h);
                if(h == 0){
                    self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,0);
                    self.questionView.hidden = YES;
                    self.titleWebView.top = 24;
                }else{
                    self.questionView.hidden = NO;
                    self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,h+20);
                    self.total_h = self.total_h+h+20;
                    self.titleWebView.top = CGRectGetMaxY(self.questionView.frame)+24;
                }
                self.exampleBgView.top = CGRectGetMaxY(self.titleWebView.frame)+21;
            }
            self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,self.total_h);
        } else {
            NSLog(@"获取 WebView 内容高度失败: %@", error.localizedDescription);
        }
    }];
}



#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.questionManager]){
        NSDictionary *dic = manager.response.content;
        NSArray *arr = [ExamQuestionModel mj_objectArrayWithKeyValuesArray:dic[@"data"]];
        for(NSInteger i = 0;i < arr.count;i++){
            ExamQuestionModel *model = arr[i];
            if([model.type isEqualToString:@"36"]){
                self.questionModel = model;
                break;
            }
        }
        [self refreshUI];
    }
    
    if([manager isEqual:self.collectSaveManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        NSString *collectId = [NSString stringWithFormat:@"%@",dic[@"data"][@"collectId"]];
        self.questionModel.collect = @"1";
        self.questionModel.collectId = collectId;
        self.collectBtn.selected = YES;
    }
    
    if([manager isEqual:self.collectDeleteManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        self.questionModel.collect = @"0";
        self.questionModel.collectId = @"";
        self.collectBtn.selected = NO;
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}


@end
